//
//  MLRequestOverlayView.m
//
//  Created by molon on 14/11/17.
//  Copyright (c) 2014年 molon. All rights reserved.
//

#import "MLRequestOverlayView.h"
#import "MolonRequestHelper.h"
#import "MLKitDefine.h"
#import "UIImage+MLKit.h"
#import "UIView+MLKit.h"
#import "NSString+MLKit.h"

@interface MLRequestOverlayView()

@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) UIButton *retryButton;

@property (nonatomic, strong) UILabel *tipsLabel;

@end

@implementation MLRequestOverlayView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        
        [self addSubview:self.indicatorView];
        [self addSubview:self.retryButton];
        [self addSubview:self.tipsLabel];
        
        self.state = MLRequestOverlayViewStateNormal;
    }
    return self;
}

- (void)dealloc
{
    //    DLOG(@"dealloc %@",NSStringFromClass([self class]));
    [self.bindHelper removeObserver:self forKeyPath:@"state" context:nil];
}

#pragma mark - getter
- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _indicatorView;
}

- (UIButton *)retryButton
{
    if (!_retryButton) {
        UIButton *button = [[UIButton alloc]init];
        //        button.backgroundColor = [UIColor yellowColor];
        [button addTarget:self action:@selector(clickRetry) forControlEvents:UIControlEventTouchUpInside];
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [button setImage:[[UIImage imageNamed:MLKIT_BUNDLE_FILE(@"刷新")] imageWithTintColor:[UIColor grayColor]] forState:UIControlStateNormal];
        _retryButton = button;
    }
    return _retryButton;
}

- (UILabel *)tipsLabel
{
    if (!_tipsLabel) {
        UILabel* label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor grayColor];
        label.font = BOLDFONT(14.0f);
        label.numberOfLines = 0;
        
        _tipsLabel = label;
    }
    return _tipsLabel;
}

#pragma mark - setter
- (void)setState:(MLRequestOverlayViewState)state
{
    _state = state;
    
    if (self.customTipsForStateBlock) {
        self.tipsLabel.text = self.customTipsForStateBlock(self,state);
    }else{
        self.tipsLabel.text = nil;
    }
    [self setNeedsLayout];
    
    if (state == MLRequestOverlayViewStateNormal) {
        self.hidden = YES;
        return;
    }
    
    self.hidden = NO;
    
    if (state == MLRequestOverlayViewStateRequestFailed) {
        [self.indicatorView stopAnimating];
        self.retryButton.hidden = NO;
        
        if (self.didGetErrorBlock) {
            self.didGetErrorBlock(self,self.bindHelper.error);
        }
    }else if(state == MLRequestOverlayViewStateRequesting){
        [self.indicatorView startAnimating];
        self.retryButton.hidden = YES;
    }
}

- (void)setBindHelper:(MolonRequestHelper *)bindHelper
{
    [_bindHelper removeObserver:self forKeyPath:@"state" context:nil];
    
    _bindHelper = bindHelper;
    
    if (_bindHelper) {
        [_bindHelper addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
    }else{
        self.state = MLRequestOverlayViewStateNormal;
    }
    
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([@"state" isEqualToString:keyPath]) {
        if ([object isEqual:self.bindHelper]) {
            if (!self.ignorePreload&&self.bindHelper.isCurrentPreloaded) {
                self.state = MLRequestOverlayViewStateNormal;
                return;
            }
            
            switch (self.bindHelper.state) {
                case MolonRequestHelperStateUnRequest:
                case MolonRequestHelperStateRequestSuccess:
                    self.state = MLRequestOverlayViewStateNormal;
                    break;
                case MolonRequestHelperStateRequestFailed:
                case MolonRequestHelperStateRequestError:
                    if (!self.ignoreFailed) {
                        self.state = MLRequestOverlayViewStateRequestFailed;
                    }else{
                        self.state = MLRequestOverlayViewStateNormal;
                    }
                    break;
                case MolonRequestHelperStateRequesting:
                    self.state = MLRequestOverlayViewStateRequesting;
                    break;
                default:
                    break;
            }
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - layout
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.indicatorView.center = CGPointMake(self.frameWidth/2, self.frameHeight/2);
    
#define kRetryButtonSide 30.0f
    self.retryButton.frame = [self midFrameWithHeight:kRetryButtonSide width:kRetryButtonSide];
    
    CGSize preferredSize = [self.tipsLabel.text sizeForWidth:self.frameWidth-10.0f withFont:self.tipsLabel.font];
    CGRect midFrame = [self midFrameWithHeight:preferredSize.height width:preferredSize.width];
    self.tipsLabel.frame = CGRectMake(midFrame.origin.x, self.retryButton.frameY-10.0f-midFrame.size.height, midFrame.size.width, midFrame.size.height);
}

#pragma mark - penetrable

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    BOOL result = [super pointInside:point withEvent:event];
    
    if (result) {
        //penetrable except button
        if (self.penetrable&&!CGRectContainsPoint(self.retryButton.frame, point)) {
            return NO;
        }
    }
    
    return result;
}

#pragma mark - event
- (void)clickRetry
{
    if (self.didClickRetryButtonBlock) {
        self.didClickRetryButtonBlock(self);
    }
}

#pragma mark - outcall
- (void)validateWithDidClickRetryButtonBlock:(void (^)(MLRequestOverlayView *view))didClickRetryButtonBlock
{
    _didClickRetryButtonBlock = didClickRetryButtonBlock;
    
    [self validate];
}


- (void)validate
{
    [self clickRetry];
}
@end
